package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class TrackReceiver {
    @Autowired
    private TrackInfoService trackInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE,durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key= MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateTrackStat(String trackstatMq, Message message, Channel channel){
        if (trackstatMq!=null){
            //        将获取的字符串转化为对象
            TrackStatMqVo trackStatMqVo = JSON.parseObject(trackstatMq, TrackStatMqVo.class);
//            获取去重消息的业务编号
            String businessNo = trackStatMqVo.getBusinessNo();
//            判断有没有消费(使用分布式锁)
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(businessNo, "1", 1, TimeUnit.HOURS);
            if (flag){
                //            调用service层方法进行处理
                try {
                    trackInfoService.updateTrackStat(trackStatMqVo);
                } catch (Exception e) {
                    e.getMessage();
                    redisTemplate.delete(businessNo);
                }
                try {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
